package cn.matezk.cloud.task;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.matezk.cloud.dao.DeviceDao;
import cn.matezk.cloud.model.Device;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.iotexplorer.v20190423.IotexplorerClient;
import com.tencentcloudapi.iotexplorer.v20190423.models.DescribeDeviceDataRequest;
import com.tencentcloudapi.iotexplorer.v20190423.models.DescribeDeviceDataResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@Slf4j
public class IccidSyncTask {
    @Autowired
    private DeviceDao deviceDao;
    @Autowired
    private IotexplorerClient tencentClient;
    @Value("${spring.profiles.active}")
    private String env;

    @Scheduled(cron = "0 0 2 * * ?")
    public void execute() {
        if (ObjectUtil.notEqual("prd", "env"))  return;
        List<String> deviceIds = deviceDao.selectIccidIsEmpty();
        for (String id : deviceIds) {
            DescribeDeviceDataRequest dataRequest = new DescribeDeviceDataRequest();
            dataRequest.setProductId(id.split("/")[0]);
            dataRequest.setDeviceName(id.split("/")[1]);
            try {
                DescribeDeviceDataResponse dataResponse = tencentClient.DescribeDeviceData(dataRequest);
                String data = dataResponse.getData();
                JSONObject obj = JSONUtil.parseObj(data);
                String iccid = obj.containsKey("iccid") ? obj.getJSONObject("iccid").getStr("Value") : "";
                if (ObjectUtil.isNotEmpty(iccid)) {
                    Device device = new Device();
                    device.setDeviceId(id);
                    device.setIccid(iccid);
                    deviceDao.updateByPrimaryKeySelective(device);
                }
                Thread.sleep(500);
            } catch (TencentCloudSDKException e) {
                log.error(e.getMessage());
            } catch (InterruptedException e) {
                log.error(e.getMessage());
            }
        }
    }
}
